
use anyhow::Result;
use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use std::borrow::Borrow;

use crate::miner::{JsonRpcResponse, JsonRpcError, SectorId};
use crate::miner::types::TaskType;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SectorStorageInfo {
    #[serde(rename(deserialize = "ID"))]
    pub id: String,
    pub urls: Vec<String>,
    pub weight: u64,
    pub can_sel: bool,
    pub can_store: bool,
    pub primary: bool,
}

pub async fn find_sector_from_storage(client: &Client<HttpConnector>, url: &str, token: &str, sector: u64) -> Result<JsonRpcResponse<Vec<SectorStorageInfo>>>{
    let sec = SectorId{number: sector, miner: 808701u64};
    let body = serde_json::json!({
                "jsonrpc": "2.0",
                "method": "Filecoin.StorageFindSector",
                "params": [sec, 1, 0, false],
                "id": 1,
            });
    let auth = format!("Bearer {}", token);
    let body = body::Body::from(body.to_string());

    let request = Request::builder()
        .uri(url)
        .header("Authorization", auth)
        .body(body)?;

    let rsp = client.request(request).await?;
    if rsp.status().is_success() {
        let buf = body::to_bytes(rsp).await?;
        let result: JsonRpcResponse<Vec<SectorStorageInfo>> = serde_json::from_slice(buf.borrow())?;
        Ok(result)
    } else {
        Err(anyhow::Error::msg(format!("http request got error response {}", rsp.status())))
    }
}